<?php
namespace app\beautiful\controller\miniapp\member;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\setting\SettingBuyModel;
use app\beautiful\model\setting\SettingIntegralModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\logic\printer\PrinterLogic;
use think\facade\Db;
class Buy extends \app\BaseController{
    
    public function init(){
        $buySetting = SettingBuyModel::where([['shop_id','=', $this->request->shopId]])->find();
        if(empty($buySetting) || $buySetting->is_open == 0){
            return $this->error('小程序未开启在线买单功能');
        }
        $return = [
            'is_open' => $buySetting->is_open,
            'is_use_coupon' => $buySetting->is_use_coupon,
            'is_integral_deduction_balance' => $buySetting->is_integral_deduction_balance,
            'is_vip_discount'  => $buySetting->is_vip_discount,
            'coupons'   => [], //可以选择的用户优惠券
            'integral_deduction_balance_limit_rate' => 0,//积分使用的上限比例
            'integral_exchange_balance' => 0, //积分抵扣余额的汇率 100积分等于多少元
            'vip_discount' => 10, //会员折扣
        ];
        if($buySetting->is_integral_deduction_balance == 1){ //允许使用积分抵扣的情况下
            $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->request->shopId]])->find();
            if(null === $SettingBalance){
                $return['is_integral_deduction_balance'] = 0;
                $return['integral_deduction_balance_limit_rate'] = 0;
            }else{
                $return['integral_deduction_balance_limit_rate'] = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比
            }
            $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->request->shopId]])->find();
            if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额
                $return['is_integral_deduction_balance'] = 0;
                $return['integral_deduction_balance_limit_rate'] = 0;
                $return['integral_exchange_balance'] = 0;
            }else{
                $return['integral_exchange_balance'] = $integralSetting->integral_exchange_balance;//汇率      
            }
        }
        if($buySetting->is_vip_discount == 1){
            if(empty($this->request->member->level_id)){
                $return['is_vip_discount'] = 0;
            }else{
                $level = $this->request->member->level;
                if(null === $level){ //折扣同样不使用
                    $return['is_vip_discount'] = 0;
                }else{
                    $return['vip_discount'] = $level->discount;
                }
            }
        }
        if($buySetting->is_use_coupon == 1){
            $today = date('Y-m-d',time());
            $coupons = MemberCouponModel::where([
                ['shop_id','=', $this->request->shopId],
                ['member_id','=', $this->request->memberId],
                ['valid_bg_time','<=',$today],
                ['valid_end_time','>=',$today],
                ['status','=',0],
            ])->limit(0,50)->select()->toArray(); //最多下发50条
            $return['coupons'] = $coupons;
        }
        return $this->success([
            'buyInfo' => $return
        ]);
    }
    
    //因为买单订单一般是面对面的订单 所以相信前台计算的价格了 不再服务端重复计算价格的设置了，严格意义是需要校验以免不法分子寻找系统漏洞
    public function buyCreateOrder(){
        $buySetting = SettingBuyModel::where([['shop_id','=', $this->request->shopId]])->find();
        if(empty($buySetting) || $buySetting->is_open == 0){
            return $this->error('小程序未开启在线买单功能');
        }
        $balance = (float)$this->request->param('balance');
        $vipBalance = (float)$this->request->param('vipBalance');
        $integral = $this->request->param('integral/d');
        $integralBalance = (float)$this->request->param('integralBalance');
        $coupon_id = $this->request->param('coupon_id/d');
        if(empty($balance) || $balance <= 0){
            return $this->error('请输入要支付的金额');
        }
        if($vipBalance < 0 || $integralBalance < 0){
            return $this->error('优惠金额不正确');
        }
        $couponBalance = 0;
        if(!empty($coupon_id)){
           if(null === $myCoupon =  MemberCouponModel::find($coupon_id)){
               return $this->error('优惠券不存在');
           }
           if($myCoupon->status == 1 || $myCoupon->money_limit > $balance){
               return $this->error('该优惠券不可用');
           }
           if($myCoupon->member_id != $this->request->memberId){
               return $this->error('该优惠券不可用');
           }
           $couponBalance = $myCoupon->coupon_money;
        }
        $youhui = $vipBalance + $integralBalance + $couponBalance;
        if($youhui >= $balance){
            return $this->error('订单创建失败,支付金额不正确');
        }
        $BuyOrderModel = new BuyOrderModel();
        $BuyOrderModel->save([
            'shop_id'           => $this->request->shopId,
            'member_id'         => $this->request->memberId,
            'balance'           => $balance,
            'vip_balance'       => $vipBalance,
            'member_coupon_id'  => $coupon_id,
            'coupon_money'      => $couponBalance,
            'use_integral'      => $integral,
            'integral_balance'  => $integralBalance,
        ]);
        return $this->success([
            'order_id' => $BuyOrderModel->buy_order_id
        ]);
    }
    //买单余额支付
    public function buyMoneyPayment(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if(null === $order = BuyOrderModel::find($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('请选择要支付的订单');
        }
        Db::startTrans();
        try{
            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 5, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->integral, 6);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->balance * 100 - $order->vip_balance * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $res = $MemberWalletLogic->useBalance($needPay, $order->balance, 5);
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->pay_type = 'money';
            $order->save();

            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('buy',$order->buy_order_id);
            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
}
